const MongoClient = require("mongodb").MongoClient;

class mongoDb {
	constructor() { }
	//连接数据库
	test(url, payload) {
		return new Promise((req, rej) => {
			try {
				console.log(url);
				MongoClient.connect(url, (err, client) => {
					if (err) {
						console.log(err);
						rej("连接数据库失败:" + err);
					}
					const database = client&&client.db(payload.sqlname);
					req(database ? "连接成功" : "数据库中没有查找到此表");
				});
			} catch (e) {
				rej("连接数据库失败:" + e);
			}
		});
	}
	connect(url, payload) {
		return new Promise((req, rej) => {
			try {
				console.log(url);
				MongoClient.connect(url, (err, client) => {
					if (err) {
						console.log(err);
						req("连接数据库失败:" + err);
					}
					const database = client.db(payload.sqlname);
					console.log("数据库链接成功");
					req(database);
				});
			} catch (e) {
				req("连接数据库失败:" + e);
			}
		});
	}
	//查询数据
	find(url, payload) {
		return new Promise(async (req, rej) => {
			try {
				this.connect(url, payload).then((db) => {
					//连接数据库返回的db对象
					console.log(payload.sqltable);
					db.collection(payload.sqltable)
						.find({})
						.toArray(function (err, result) {
							if (err) {
								rej(err);
								return;
							}
							req(result);
						});
				});
			} catch (e) {
				rej("获取数据库数据失败:" + e);
			}
		});
		// return new Promise((resolve, reject) => {
		// 	this.connect().then((db) => {
		// 		//连接数据库返回的db对象
		// 		db.collection(collectionName)
		// 			.find(json)
		// 			.toArray(function(err, result) {
		// 				if (err) {
		// 					reject(err);
		// 					return;
		// 				}
		// 				resolve(result);
		// 			});
		// 	});
		// });
	}
}

const testmongo = (url, payload) => {
	return new Promise(async (resolve) => {
		const newdb = new mongoDb();
		const dbtestmsg = await newdb.test(url, payload);
		resolve(dbtestmsg);
	});
};
const gettarget = (url, payload) => {
	return new Promise(async (resolve) => {
		const newdb = new mongoDb();
		const dbtestmsg = await newdb.find(url, payload);
		resolve(dbtestmsg);
	});
};
module.exports = { testmongo, gettarget };
